package org.voyager.service.wx.web.wx;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.voyager.service.wx.common.result.JsonResult;
import org.voyager.service.wx.config.WxMpConfiguration;
import org.voyager.service.wx.config.WxMpProperties;
import org.voyager.service.wx.model.WxRequestBO;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @author Edward
 */
@RestController
@RequestMapping("/wx/jsapi")
public class WxJsapiController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    WxMpProperties wxMpProperties;

    @PostMapping(value = "/getTicket")
    @ResponseBody
    //public JsonResult getTicket(@RequestJson(value = "url") String url) {
    public JsonResult getTicket(@RequestBody WxRequestBO bo) {
        JsonResult jsonResult = JsonResult.ok();
        WxMpService mpService = WxMpConfiguration.getMpService();

        try {
            WxJsapiSignature wxJsapiSignature = mpService.createJsapiSignature(URLDecoder.decode(bo.getUrl(), "UTF-8"));
            jsonResult.put("appId", wxJsapiSignature.getAppId())
                    .put("nonceStr", wxJsapiSignature.getNonceStr())
                    .put("timestamp", wxJsapiSignature.getTimestamp())
                    .put("url", wxJsapiSignature.getUrl())
                    .put("signature", wxJsapiSignature.getSignature());
        } catch (WxErrorException e) {
            e.printStackTrace();
            return JsonResult.error();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return JsonResult.error();
        }

        return jsonResult;
    }
}
